package com.elminster.datastruct;

import java.util.ArrayList;

public class PriorityList<E extends Comparable<E>> extends ArrayList<E> {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -2130398732774700347L;

    public boolean add(E e) {
        int idx;
        if (0 == this.size()) {
            idx = 0;
        } else {
            idx = getIndex(e, 0, this.size() - 1);
        }
        super.add(idx, e);
        return true;
    }
    
    private int getIndex(E e, int start, int end) {
        if (start >= end) {
            if (this.get(start).compareTo(e) > 0) {
                return start + 1;
            } else {
                return start;
            }
        }
        int middle = (start + end) / 2;
        if (this.get(middle).compareTo(e) > 0) {
            return getIndex(e, middle + 1, end);
        } else if (this.get(middle).compareTo(e) < 0) {
            return getIndex(e, start, middle - 1);
        } else {
            return middle + 1;
        }
    }
}
